from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from werkzeug.utils import secure_filename
import os
import tempfile
import uuid
from datetime import datetime
import logging

from .services.converter_service import ConverterService
from .services.file_service import FileService
from .config import config
from .config_manager import config_manager

def create_app(config_name=None):
    """创建Flask应用"""
    app = Flask(__name__)
    
    # 获取配置名称
    if config_name is None:
        config_name = config_manager.get_environment()
    
    # 应用配置
    app.config.from_object(config.get(config_name, config['default'])())
    
    # 启用CORS
    CORS(app, origins=config_manager.get_cors_origins())
    
    # 配置日志
    logger = logging.getLogger(__name__)
    
    # 初始化服务
    converter_service = ConverterService()
    file_service = FileService(
        upload_folder=config_manager.get_upload_folder(),
        temp_folder=config_manager.get_temp_folder()
    )
    
    @app.route('/api/health', methods=['GET'])
    def health_check():
        """健康检查接口"""
        return jsonify({
            'status': 'ok',
            'timestamp': datetime.now().isoformat(),
            'version': '1.0.0',
            'environment': config_manager.get_environment(),
            'config': {
                'max_file_size': config_manager.get_max_file_size(),
                'allowed_extensions': list(config_manager.get_allowed_extensions()),
                'supported_formats': config_manager.get_supported_formats()
            }
        })
    
    @app.route('/api/convert', methods=['POST'])
    def convert_document():
        """文档转换接口"""
        try:
            if 'file' not in request.files:
                return jsonify({'error': '没有上传文件'}), 400
            
            file = request.files['file']
            if file.filename == '':
                return jsonify({'error': '文件名为空'}), 400
            
            source_format = request.form.get('source_format')
            target_format = request.form.get('target_format')
            options = request.form.get('options', '{}')
            
            if not source_format or not target_format:
                return jsonify({'error': '缺少转换格式参数'}), 400
            
            # 验证文件格式
            if not file_service.is_allowed_file(file.filename, config_manager.get_allowed_extensions()):
                return jsonify({'error': '不支持的文件格式'}), 400
            
            # 保存上传的文件
            file_id = str(uuid.uuid4())
            input_path = file_service.save_uploaded_file(file, file_id)
            
            # 执行转换
            output_path = converter_service.convert(
                input_path, source_format, target_format, options
            )
            
            # 返回转换后的文件
            return send_file(
                output_path,
                as_attachment=True,
                download_name=f"converted_{file_id}.{target_format}"
            )
            
        except Exception as e:
            logger.error(f"转换失败: {str(e)}")
            return jsonify({'error': f'转换失败: {str(e)}'}), 500
    
    @app.route('/api/batch-convert', methods=['POST'])
    def batch_convert():
        """批量转换接口"""
        try:
            files = request.files.getlist('files')
            if not files:
                return jsonify({'error': '没有上传文件'}), 400
            
            source_format = request.form.get('source_format')
            target_format = request.form.get('target_format')
            options = request.form.get('options', '{}')
            
            results = []
            for file in files:
                try:
                    if not file_service.is_allowed_file(file.filename, config_manager.get_allowed_extensions()):
                        results.append({
                            'filename': file.filename,
                            'status': 'error',
                            'error': '不支持的文件格式'
                        })
                        continue
                    
                    file_id = str(uuid.uuid4())
                    input_path = file_service.save_uploaded_file(file, file_id)
                    output_path = converter_service.convert(
                        input_path, source_format, target_format, options
                    )
                    results.append({
                        'filename': file.filename,
                        'status': 'success',
                        'download_url': f'/api/download/{file_id}'
                    })
                except Exception as e:
                    results.append({
                        'filename': file.filename,
                        'status': 'error',
                        'error': str(e)
                    })
            
            return jsonify({'results': results})
            
        except Exception as e:
            logger.error(f"批量转换失败: {str(e)}")
            return jsonify({'error': f'批量转换失败: {str(e)}'}), 500
    
    @app.route('/api/formats', methods=['GET'])
    def get_supported_formats():
        """获取支持的格式列表"""
        return jsonify({
            'formats': config_manager.get_supported_formats(),
            'conversions': config_manager.get_conversion_matrix()
        })
    
    @app.route('/api/config', methods=['GET'])
    def get_config():
        """获取前端配置"""
        return jsonify({
            'api_base_url': config_manager.get_api_base_url(),
            'max_file_size': config_manager.get_max_file_size(),
            'allowed_extensions': list(config_manager.get_allowed_extensions()),
            'supported_formats': config_manager.get_supported_formats(),
            'conversion_matrix': config_manager.get_conversion_matrix()
        })
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(
        host=config_manager.get_server_host(),
        port=config_manager.get_server_port(),
        debug=config_manager.get_server_debug()
    ) 